package com.apigen.platform.controller;

import com.apigen.platform.common.Result;
import com.apigen.platform.service.TemplateRenderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 模板管理控制器
 *
 * @author API Generator Platform
 * @since 2025-10-03
 */
@Slf4j
@RestController
@RequestMapping("/api/templates")
@RequiredArgsConstructor
@Tag(name = "模板管理", description = "代码生成模板相关接口")
public class TemplateController {

    private final TemplateRenderService templateRenderService;

    @GetMapping("/{frameworkType}")
    @Operation(summary = "获取框架模板列表", description = "获取指定框架支持的所有模板")
    public Result<List<Map<String, Object>>> getFrameworkTemplates(
            @Parameter(description = "框架类型", example = "spring-boot") @PathVariable String frameworkType) {
        try {
            List<Map<String, Object>> templates = templateRenderService.getFrameworkTemplates(frameworkType);
            return Result.success(templates);
        } catch (Exception e) {
            log.error("获取框架模板列表失败: {}", e.getMessage());
            return Result.error("获取模板列表失败: " + e.getMessage());
        }
    }

    @GetMapping("/{frameworkType}/{templateName}")
    @Operation(summary = "获取模板内容", description = "根据框架类型和模板名称获取模板文件内容")
    public Result<String> getTemplateContent(
            @Parameter(description = "框架类型", example = "spring-boot") @PathVariable String frameworkType,
            @Parameter(description = "模板名称", example = "controller.hbs") @PathVariable String templateName) {
        try {
            String content = templateRenderService.getTemplateContent(frameworkType, templateName);
            return Result.success(content);
        } catch (Exception e) {
            log.error("获取模板内容失败: {}", e.getMessage());
            return Result.error("获取模板内容失败: " + e.getMessage());
        }
    }

    @PostMapping("/render")
    @Operation(summary = "渲染模板", description = "使用指定数据渲染模板内容")
    public Result<String> renderTemplate(@RequestBody Map<String, Object> request) {
        try {
            String templateContent = (String) request.get("templateContent");
            @SuppressWarnings("unchecked")
            Map<String, Object> data = (Map<String, Object>) request.get("data");
            
            String result = templateRenderService.renderTemplate(templateContent, data);
            return Result.success(result);
        } catch (Exception e) {
            log.error("渲染模板失败: {}", e.getMessage());
            return Result.error("渲染模板失败: " + e.getMessage());
        }
    }
}